<template>
	<view>
		<loading :showLoaded.sync="showLoaded"></loading>
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		 <!-- <custom-nav-bar :nav-bar-info="navBarInfo" /> -->
		<tabBar v-if="customTabbar === 1 && tabbarTimeout" :nowPages.sync="nowPages"></tabBar>
		<floorNav v-if="floorNavData" :floorNavData="floorNavData" @childEvent="select"></floorNav>
		<view :style="{paddingBottom: (isIpx ? 75 : 55) + 'px'}">
			<view v-if="utoolsData && utoolsClassGoodsLists" :style="utoolsStyle"  @touchstart="onTouchStart"
				@touchmove="onTouchMove" @touchend="onTouchEnd">
				<!-- <view :style="{height:navBarHeight+'rpx'}"></view> -->
				<!-- <view v-if="utoolsData && utoolsClassGoodsLists"  > -->
				<utools-parse id="utools-parse" page="category" @triggerComponent="onTriggerComponent"
					@utoolsEvents="onSetTrackIndeData" @setPanel="setPanel" :utools-data="utoolsData"
					@onAddCart="onAddCart"></utools-parse>
			</view>
		</view>
		<register-widget ref="registerWidgetRef" location="category" @finish="onRegisterWidgetFinish" :tsActId="tsActId"
			@registerSuccess='registerSuccess' />
		<cart-toast v-if="showCartMsg" :cartMessage='cartMessage' :cartStatus="cartStatus"></cart-toast>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
	</view>
</template>

<script>
	let observer = null;
	let observer2 = null;
	import api from '@/api/api';
	import tip from '@/utils/tip';
	import util from '@/utils/util.js'
	import loading from '@/components/common/loading';
	// import itemsSlideslipNew from './itemsSlideslipNew.vue';
	// import itemsTileNew from './itemsTileNew.vue';
	import TabBar from '@/components/common/tabbar';
	import NavBar from '@/components/common/navbar';
	import FloorNav from './components/floorNav';
	import registerWidget from "@/components/register/register-widget.vue";
	import CartToast from '@/components/common/cartToast.vue';
	import {
		SYSTEM_INFO,
		MERCHANT_INFO,
		CUSTOMER_INFO,
		USER_INFO,
		CART_KEY
	} from '@/utils/constant';
	import {
		reportEvent,
		getEventIdByNavName,
		EVENT_ID
	} from '@/utils/ab-test.js';

	export default {
		components: {
			// itemsSlideslipNew: itemsSlideslipNew,
			// itemsTileNew: itemsTileNew,
			loading: loading,
			tabBar: TabBar,
			navBar: NavBar,
			floorNav: FloorNav,
			registerWidget: registerWidget,
			CartToast: CartToast
		},
		data() {
			return {
				tabbarTimeout: false,
				customTabbar: -1,
				nowPages: '',
				isShowCustomNavBar: true,
				// 组件所需的参数
				navbarData: {
					showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
					title: '商城', //导航栏 中间的标题
					newLogo: 'https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/blackSearch.png',
					leftIcon: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/blackSearch.png",
					isTopFixed: false
				},
				navBarInfo: {
				  page: "index",
				  logo: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/red-logo.png",
				  leftIcon: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/blackSearch.png",
				  backgroundColor: "#ffffff"
				},
				storeProductList: [],
				rootcateList: [],
				afterPage: '',
				contentLsitObj: {},
				showLoaded: true,
				preview: false,
				isIpx: true,
				utoolsData: null,
				cateProductList: [],
				floorNavData: null,
				query: wx.createSelectorQuery(),
				floor: 0,
				ofseTop: 0,
				panelList: null,
				isShowPanel: false,
				utoolsClassGoodsLists: null,
				tsActId: '',
				showCartMsg: false,
				cartMessage: '',
				cartStatus: false,
				scrollTop: 0,
				isPNav: false,
				utoolsStyle: 'position: fixed',
				startX: 0,
				startY: 0,
				idList: '',
				disappearfold: null,
				timer: null,
				utoolsShopLists: [],
				trackIndeData: {},
				timeouter: null,
				ballotGoodsLists: [],
				balloutReload: false,
				shareImage: '', //页面分享图片
				shareTitle: '', //页面分享标题
				pagePath: '', //页面分享路径
				pageQuery: '', //页面分享参数
				navBarHeight: '',

			}
		},
		async onLoad(option = {}) {

			await this.$onLaunched;
			let that = this;
			this.getPageShareData();
			let pages = getCurrentPages();
			var currPage = pages[pages.length - 1];
			this.nowPages = currPage.route;

			await this.init(option.utid)


			this.showLoaded =false
			// }).catch((err) => {});
		},
		onUnload() {
			if (observer) observer.disconnect()
		},
		onHide() {
			if (observer) observer.disconnect()
		},
		onShow() {
			try {
				let that = this;
				this.isIpx = getApp().globalData.isIpx;
				that.customTabbar = this.$programSetting.customTabbar ? 1 : 0
				this.preview = getApp().globalData.cmsPreview ? getApp().globalData.cmsPreview : false;
				let systemInfo = uni.getSystemInfoSync();
				let rect = uni.getMenuButtonBoundingClientRect ? uni.getMenuButtonBoundingClientRect() : null; //胶囊按钮位置信息
				let pixelRatio1 = 750 / wx.getSystemInfoSync().windowWidth;
				let navBarHeight = (function() {
					//导航栏高度
					let gap = rect.top - systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
					return 2 * gap + rect.height;
				})();

				this.ofseTop = navBarHeight + 200 / pixelRatio1 + systemInfo.statusBarHeight;
				this.navBarHeight = navBarHeight + systemInfo.statusBarHeight +112/pixelRatio1 ;
				getApp().cl_tracker.track('mini_program_view', {
					path: '/pages/item/categoryNew',
					pageName: '商城',
				});
				that.$commonSensors.commonPageView('PLPView')
				setTimeout(() => {
					that.tabbarTimeout = true;
				}, 600)
				// 首页横幅utools数据拉取
				if (this.balloutReload) {
					this.checkHasBallout();
				}

				let h = systemInfo.windowHeight / 2
				setTimeout(async () => {
					observer = uni.createIntersectionObserver(that, {
						observeAll: true,
						thresholds: [0.1],
						initialRatio: 0
					});
					observer.relativeToViewport({
						top: 0,
						left: 0,
						right: 0,
						bottom: -h,
						// width: wx.getSystemInfoSync().windowWidth,
						// height:	 h*2,
					}).observe('#utools-parse >>> .foldPanel', (res) => {

						if (res.intersectionRatio > 0.1 || res.intersectionRatio == 0.1) {
							let dom = this.selectComponent(`#utools-parse >>> #${res.id}`)
							if (dom.data.isFold) {
								this.trackProductBannerExpo2(dom.data.mf_data)
							}
							if (!this.idList.includes(res.id)) {
								this.idList += res.id
								this.setPanel(null, res.id)
							}
						}
					})
						this.getBalloutText()
				}, 4000)
			} catch (e) {
				console.log("############ onShow----error:", e)
			}
		},
		onPageScroll(e) {
			// 页面滚动时执行
			this.scrollTop = e.scrollTop
			if (e.scrollTop > 1) {
				this.scrollFloor(e.scrollTop + 10)
			}
		},
		methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
			/**
			 * 查询分享数据
			 * @param {Object} option
			 */
			async getPageShareData() {
				try {
					const res = await this.$commonFunction.getShareinfoByCode('category');
					this.shareImage = res.shareImage;
					this.shareTitle = res.shareTitle;
					this.pagePath = res.pagePath; //  当前页面路由
					this.pageQuery = res.pageQuery; //  当前页面url参数
				} catch (e) {}
			},
			async setTopBar(item) {
				if (item && !this.ballotGoodsLists.find(ite => item.domId == ite.domId)) {
					this.ballotGoodsLists.push(item);
				}
				this.balloutReload = true;
			},
			async checkHasBallout() {
				try {
					const that = this;
					if (this.balloutReload && this.ballotGoodsLists.length) {
						// ############   抽签购活动组件需要 重新加载  ############
						for (let i = 0; i < this.ballotGoodsLists.length; i++) {
							let domRef = that.selectComponent(`#utools-parse >>> #${this.ballotGoodsLists[i].domId}`)
							if (domRef) domRef.balloutInit();
						}
					}
				} catch (e) {}
			},

			async getServerTime() {
				let nowTime = new Date().getTime() / 1000;
				try {
					const json = await api.getServerTime({
						method: "POST",
						query: {},
					});
					if (json.code === 1000 && json.data) {
						let time = JSON.parse(json.data);
						nowTime = time.server_date / 1000;
					}
					return nowTime;
				} catch (e) {
					return nowTime;
				}
			},
			//  抽签购文案修改
			async getBalloutText() {
				try {
					let that = this;
					let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					const recordListResult = await api.recordList({
						header: {
							jwt: customerInfo.jwt || jwt
						},
						query: {
							page_no: 1,
							page_size: 100,
						}
					});
					if (recordListResult.code == 1000 && recordListResult.data && recordListResult.data.total) {
						let b_str = ''
						let b_lists = [];
						let _listData = recordListResult.data.content;
						let _nowTime = await this.getServerTime();
						let systemInfo = uni.getStorageSync(SYSTEM_INFO);
						let isIos = systemInfo.system.indexOf('iOS');
						let goodsList = [];
						let _lists = ['恭喜中签','待支付'];

						for (let i = 0; i < _listData.length; i++) {
							let activityStopTime;
							if (isIos == 0) {
								activityStopTime = new Date(_listData[i].activityStopTime.replace(/-/g, '/')).getTime() / 1000;
							} else {
								activityStopTime = new Date(_listData[i].activityStopTime).getTime() / 1000;
							}
							if (activityStopTime > _nowTime && _listData[i].luckyCode && _lists.includes(_listData[i].status)) {

								//  查询商品详情 获取短名
								const goodsInfo = await this.getGoodsDetail(merchantInfo, _listData[i].itemId);
								let _name = _listData[i].itemName;
								if (goodsInfo.code == 1000 && goodsInfo.data && goodsInfo.data.frontProperties &&goodsInfo.data.frontProperties[0]) {
									b_lists.push(goodsInfo.data.frontProperties[0]);
									goodsList.push( {itemId:_listData[i].itemId,valueId: goodsInfo.data.frontProperties[0].valueId});
									_name = goodsInfo.data.frontProperties[0].subtitle || _name;
								}
								b_str = `恭喜您中签${_name}购买资格`;
							}
						}
						if (b_lists.length > 1) {
							const numArr = ['两', '三', '四', '五', '六', '七', '八', '九', '十'];
							let num = numArr[b_lists.length - 2];
							b_str =`恭喜您获得${b_lists[0].subtitle }等${num}件商品购买资格购买资格`;
						}
						if (b_str) {
							let dom = this.selectComponent(`#utools-parse >>> #foldPanelTop`)
							if (dom) dom.updataData(b_str, goodsList)
						}
					}
				} catch (e) {
					console.log("###########getBalloutText-error", e)
				}
			},
			onSetTrackIndeData(e) {
				const {
					data,
					type
				} = e.target.data
				if (type == 'rewriteTabCurrIndex') {
					this.trackIndeData[data.name] = data.currIndex
				}
				//
			},
			async init(id = null) {

				// 模板数据
				this.utoolsData = await this.getHomeUtoolsData(id)

				if (this.utoolsData) {
					this.disappearfold = this.utoolsData.children.find(item => item.label1 == "disappear_fold")

					if (!this.disappearfold) {
						this.utoolsStyle = ''
					}
					//商品
					this.utoolsClassGoodsLists = await this.getCateGoods(this.utoolsData?.classId || 8066)
					if (this.disappearfold && this.utoolsClassGoodsLists) {
						this.trackProductBannerExpo(this.disappearfold.id)
					}
					setTimeout(async () => {
						this.floorNavData = await this.initloorNavigation()
					}, 0)
					// //活动
					// let list = await  this.drawControl(temporaryProductList)
					//shangpin曝光买点
					this.exposeSkuTrack(this.utoolsClassGoodsLists)

				}
				return null
			},

			onTouchStart(e) {
				let _p = e.changedTouches || [];
				if (_p && _p[0]) {
					const _tp = _p[0];
					this.startY = _tp.clientY;
					this.startX = _tp.clientX;
				}
			},
			onTouchMove(e) {},
			async onTouchEnd(e) {
				let _p = e.changedTouches || [];
				if (_p && _p[0]) {
					const _tp = _p[0];
					let y = Math.abs(this.startY - _tp.clientY)
					let x = Math.abs(this.startX - _tp.clientX)
					const _tn = _tp.clientY - this.startY;
					if (_tn < -20 && y > (x + 10) && !this.isPNav && this.disappearfold) {
						// this.isPNav = true;
						await this.setPNav(true);
						setTimeout(() => {
							// this.utoolsStyle = '';
							this.scrollFloor(10)
						}, 500)

					}

					if (_tn > 20 && y > (x + 10) && this.isPNav && this.disappearfold && this.scrollTop < 1) {
						this.scrollFloor(0)
						// this.isPNav = false
						this.setPNav(false)
						// this.utoolsStyle = 'position: fixed'
						this.trackProductBannerExpo(this.disappearfold.id)
					}
				}
			},
			//抽签时间控制
			async drawControl(listarr) {
				return new Promise(async (resolve, reject) => {
					let listArr = listarr
					for (let i = 0; i < listArr.length; i++) {
						if (listArr[i].activitySelection) {
							listArr[i].activitySelection.dateStatus = await this.timeStatus(listArr[i])
								.dateStatus
							listArr[i].activitySelection.joinStatus = await this.timeStatus(listArr[i])
								.joinStatus
						}
					}
					let productList = listArr
					resolve(productList)
				})
			},
			timeStatus(item) {
				let nowTime = new Date().getTime()
				let drawStartTime = item.activitySelection.activitySelectionStartTime
				let drawEndTime = item.activitySelection.activitySelectionEndTime
				let promulgateTime = item.activitySelection.promulgateTime
				let buyEndTime = item.activitySelection.buyEndTime
				let activityStopTime = item.activitySelection.activityStopTime
				let obj = {}
				let showTime;
				let showText;
				if (nowTime < drawStartTime) {
					showTime = util.timeFormat(drawStartTime) + ' 开始登记'
					showText = '未开放登记信息'
				} else if (nowTime > drawStartTime && nowTime < drawEndTime) {
					showTime = util.timeFormat(drawEndTime) + ' 登记结束'
					showText = '开放登记信息'
				} else if (nowTime > drawEndTime && nowTime < promulgateTime) {
					showTime = util.timeFormat(promulgateTime) + ' 公布结果'
					showText = '等待公布结果'
				} else if (nowTime > promulgateTime && nowTime < buyEndTime) {
					showText = '结果已公布'
					showTime = util.timeFormat(buyEndTime) + ' 活动结束'
				} else if (nowTime > buyEndTime && nowTime < activityStopTime) {
					showTime = util.timeFormat(buyEndTime) + ' 活动结束'
					showText = '活动已结束'
				} else {
					showTime = ''
					showText = ''
				}
				obj.dateStatus = showTime
				obj.joinStatus = showText
				return obj
			},
			enterProductList(item, area) {
				if (area == 'banner') {
					if (!!item.jumppath) {
						if (item.jumppath.indexOf('/home') !== -1 || item.jumppath.indexOf('category/category') !== -1 ||
							item
							.jumppath.indexOf('/cart') !== -1 || item.jumppath.indexOf('/info') !== -1 || item.jumppath
							.indexOf(
								'/categoryNew') !== -1) {
							uni.reLaunch({
								url: item.jumppath
							})
						} else {
							uni.navigateTo({
								url: item.jumppath
							})
						}
					} else {
						// 不做默认调整
						// uni.navigateTo({
						//   url: '/pages/item/categoryList?id=' + item.foreignId + '&navName=' + item.navName
						// })
					}
				} else {
					uni.navigateTo({
						url: '/pages/item/categoryList?id=' + item.foreignId + '&navName=' + item.navName
					})
				}

				reportEvent(EVENT_ID.CATEGORY.SHANG_CHENG);
				reportEvent(getEventIdByNavName(item.navName));
				// 商城-点击-商城板块 不凡甄选/日常小酌/璀璨系列/免税专供埋点
				let clTrackPrams = {
					'c_block_name': item.navName,
					'c_click_area': area,
				}
				getApp().commonClTrack('c_ebmp_click_block', clTrackPrams);
			},

			async getHomeUtoolsData(id = null) {

				let json;
				if (id) {
					json = await api.getUtoolsJsonP({
						utoolsId: id,
						type: 'category'
					});
				} else {
					json = await api.getUtoolsJson({
						type: 'category'
					});
				}
				return json.success && json?.data ? JSON.parse(json.data) : null
			},

			//  查询首页商品分类列表
			async getCateGoods(class_id, is_sort) {
				try {
					//获取商品
					let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '',
						'', '')
					let cateProductList = res.data.content; // 商品列表
					//sku实时库存查询
					let skuCodeList = [],
						goodsQ = [];
					for (let i = 0; i < cateProductList.length; i++) {
						skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
					}

					if (skuCodeList.length) {
						skuCodeList = await this.setSkuCodeList(skuCodeList)
						for (let i = 0; i < skuCodeList.length; i++) {
							let reset = await this.getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList[i]);
							goodsQ = reset.length ? goodsQ.concat(reset) : goodsQ
						}
					}

					// 策略价格
					let list = [];
					cateProductList = cateProductList.map(async item => {
						item.frontQty = 0
						let res = await this.$commonFunction.priceRulesDeal(item.strategies, item
							.itemmCode)
						if (goodsQ && goodsQ.length) {
							for (let i = 0; i < goodsQ.length; i++) {
								if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i]
									.availableQty > 0) {
									item.frontQty += goodsQ[i].availableQty
								}
							}
						}
						if (res.price !== 0) {
							if (item.itemCode == res.itemCode) {
								item.price = res.price
							}
						}
						if (res.rulesArr.length > 0) {
							if (item.itemCode == res.itemCode) {
								item.rulesArr = res.rulesArr
							}
						}
						list.push(item)
						return item
					})
					return list
				} catch (err) {
					return null
				}
			},

			async setSkuCodeList(skuCodeList) {
				if (skuCodeList.length < 21) {
					return [skuCodeList]
				} else {
					const result = skuCodeList.flatMap((value, index, array) => {
						if (index % 20 === 0) {
							return [array.slice(index, index + 20)];
						}
						return [];
					});
					return result
				}
			},

			async getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList) {

				let reset = await api.getAvailableBatchQty({
					method: "POST",
					header: {
						'jwt': customerInfo.jwt,
						'content-type': 'application/json'
					},
					// query: JSON.stringify(skuCodeList)
					query: skuCodeList
				}, merchantInfo.cloudMerchantId);
				if (reset.msg == "SUCCESS" && reset?.data?.length) {
					return reset.data.filter(item => item.availableQty > 0)
				} else {
					return []
				}
			},

			//商品曝光expose_sku
			exposeSkuTrack(cateProductList) {
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
				for (let i = 0; i < cateProductList.length; i++) {
					if (cateProductList[i].skuCodes !== undefined) {
						this.$sr.track('expose_sku_component', {
							sku: {
								sku_id: cateProductList[i].skuCodes[0].toString(),
								sku_name: cateProductList[i].itemName // 若商品无sku_name时，可传spu_name信息
							},
							spu: {
								spu_id: !!uni.getStorageSync('openOuterItemId') ? cateProductList[i].outerItemId :
									!
									!uni.getStorageSync('youshuOpencc') ? cateProductList[i].frontCode
									.toString() : cateProductList[i].itemCode.toString(),
								spu_name: !!uni.getStorageSync('youshuOpencc') ? cateProductList[i].itemName +
									cateProductList[i].valueName : cateProductList[i]
									.itemName // 若商品无spu_name时，可传sku_name信息
							},
							sku_category: [{
								sku_cat_id: cateProductList[i].categoryId.toString(),
								sku_cat_name: '全部商品',
								sku_parent_cat_id: 'null' // 若已是顶级类目，传"null"
							}],
							"shipping_shop": {
								"shipping_shop_id": merchantInfo.cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
								"shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
							},
							sale: {
								original_price: parseFloat(cateProductList[i].price), // 对接智慧零售入口必传
								current_price: parseFloat(cateProductList[i].price) // 对接智慧零售入口必传
							},
							primary_image_url: cateProductList[i].majorUrl
						});
					}
				}
			},


			async filterUtoolsShopLists(data, key, value) {
				try {
					if (data && data[key] && data[key] === value) {
						this.utoolsShopLists.push(data)
						return true;
					} else if (data && data.children && data.children.length) {
						for (let i = 0; i < data.children.length; i++) {
							if (data.children[i]) {
								await this.filterUtoolsShopLists(data.children[i], key, value);
							}
						}
					}
					return null;
				} catch (e) {}
			},
			//  线上精选神策埋点
			async trackProductBannerExpo(id) {
				try {
					this.utoolsShopLists = [];
					const uData = this.utoolsData.children.filter(it => it.id == id)[0];
					if (uData && uData.type) {
						//  首页神策埋点 商品列表筛选
						await this.filterUtoolsShopLists(uData, 'type', 'commodityList');
						let index = this.trackIndeData[uData.name1 + 'tab'] || 0
						let datas = this.utoolsShopLists[index] || null;
						if (datas && datas.children && datas.children.length && datas.trackingParams) {
							let _trackData = JSON.parse(datas.trackingParams);
							if (_trackData.name && _trackData.data) {
								let product_sku_list = [];
								let product_name_list = [];
								datas.children.forEach(item => {
									let goods = this.utoolsClassGoodsLists.find(it => it.itemId == item
										.itemId);
									if (goods) {

										if (goods.skuCodes && goods.skuCodes[0]) product_sku_list.push(goods
											.skuCodes[0]);
										if (goods.itemName) product_name_list.push(goods.itemName);
									}
								})
								if (product_sku_list.length && product_name_list.length) {
									_trackData.data.product_sku_list = product_sku_list;
									_trackData.data.product_name_list = product_name_list;
									this.$commonSensors.lithaTrack.cTrack(_trackData.name, _trackData.data)
								}
							}
						}
					}
				} catch (e) {
					
				}
			},
			//  线上精选神策埋点
			async trackProductBannerExpo2(uData) {
				try {
					this.utoolsShopLists = [];
					// this.utoolsData.children.forEach
					if (uData && uData.type) {
						//  首页神策埋点 商品列表筛选
						await this.filterUtoolsShopLists(uData, 'type', 'commodityList');

						let datas = this.utoolsShopLists[0] || null;
						if (datas && datas.children && datas.children.length && datas.trackingParams) {
							let _trackData = JSON.parse(datas.trackingParams);
							if (_trackData.name && _trackData.data) {
								let product_sku_list = [];
								let product_name_list = [];
								datas.children.forEach(item => {
									let goods = this.utoolsClassGoodsLists.filter(it => it.itemId == item
										.itemId)[0];

									if (goods) {

										if (goods.skuCodes && goods.skuCodes[0]) product_sku_list.push(goods
											.skuCodes[0]);
										if (goods.itemName) product_name_list.push(goods.itemName);
									}
								})
								if (product_sku_list.length && product_name_list.length) {
									_trackData.data.product_sku_list = product_sku_list;
									_trackData.data.product_name_list = product_name_list;
									this.$commonSensors.lithaTrack.cTrack(_trackData.name, _trackData.data)
								}
							}
						}
					}
				} catch (e) {}
			},
			//初始化楼层-------------------------------------------

			async initloorNavigation() {
				// //楼层数据
				let floorChildren = await this.selectAllComponents("#utools-parse >>> .floor")
				let floorChildrenDom = await this.getDoc()

				let floorNavData = [];
				let height = 0;
				let num = 1
				if (floorChildren) {
					if (this.disappearfold) {
						floorChildren = [{
							data: {
								mf_data: this.disappearfold
							}
						}, ...floorChildren]
						num = 2
					}
					// let isSelect =false;
					for (let i = 0; i < floorChildren.length; i++) {
						let item = floorChildren[i]
						height += (floorChildrenDom[i - num]?.height - 2 || (i * 4))
						if (i == floorChildren.length - 1) {
							height = height - 100
						}

						item = {
							i: i,
							name: item.data.mf_data.name1,
							id: item.data.mf_data.id,
							isSelect: i == this.floor,
							top: height || 0,
							label1: item.data.mf_data?.boxType == "floor" ? item.data.mf_data.label1 : item.data
								.mf_data.name1,
							type: item.data.mf_data.boxType || 'disappear_fold'
						}
						floorNavData.push(item)
					}
				}

				return floorNavData
			},
			getDoc(e) {
				let that = this;
				return new Promise(async (resolve, reject) => {
					that.query.selectAll(`#utools-parse >>> .floor`).boundingClientRect(function(res) {
						resolve(res)
					}).exec()
				})
			},
			//设置楼层---------------------------------
			async select(index) {
				if (index == this.floor) return;
				if (this.utoolsStyle == 'position: fixed') {
					// this.utoolsStyle = ''
					// this.isPNav = true;
				  await	this.setPNav(true);
					setTimeout(() => {
						wx.pageScrollTo({
							selector: `#utools-parse >>> #${this.floorNavData[index].id}`,
							// scrollTop: this.floorNavData[index].top- this.ofseTop,
							offsetTop: -this.ofseTop + 4,
							duration: 0,
							complete: () => {
								// this.setfloor()
							}
						})
					}, 600)
				} else {
					let f = this.floorNavData[index]
					if (f.type == "floor") {
						wx.pageScrollTo({
							selector: `#utools-parse >>> #${this.floorNavData[index].id}`,
							// scrollTop: this.floorNavData[index].top- this.ofseTop,
							offsetTop: -this.ofseTop + 4,
							duration: 0,
							complete: () => {
								// this.setfloor()
							}
						})
					} else {
						wx.pageScrollTo({
							scrollTop: 0,
							duration: 0,
							complete: () => {
								this.scrollFloor(0)
								// this.isPNav = false
								this.setPNav(false)
								// this.utoolsStyle = 'position: fixed'

							}
						})
						this.trackProductBannerExpo(this.disappearfold.id)
					}


				}



			},
			setfloor() {
				this.floorNavData = this.floorNavData.map((item, i) => {
					item.isSelect = this.floor == i
					if (item.isSelect) {
						this.$commonSensors.lithaTrack.crTrack('PLPView', {
							tab_name: item.name
						});

						if (item.label1 == 'hasShopLists') {

							this.trackProductBannerExpo(item.id)
						}
					}

					return item
				})
			},
			scrollFloor(scrollTop) {
				this.timer && clearTimeout(this.timer), this.timer = null;
				this.timer = setTimeout(() => {
					let arr = this.floorNavData;
					let floor = 0;
					let arr2 = arr.filter(item => item.top < scrollTop || item.top == scrollTop)
					floor = arr2.length - 1 < 0 ? 0 : arr2.length - 1

					if (floor != this.floor) {
						this.floor = floor;
						this.setfloor()
					}
				}, 50)
				return null
			},
			//--------------------------------------------
			//设置顶部吸顶tap
			async setPNav(isPNav) {
				let dom = this.selectComponent(`#utools-parse >>> #foldPanelTop`)
				let a = dom.select(isPNav)
				this.isPNav = isPNav
				if(isPNav) {
					this.utoolsStyle = ''
				}else {
					this.utoolsStyle = 'position: fixed'
				}
				return a
				//楼层数据
			},
			//设置折叠------------------------
			async setPanel(d = null, id) {
				const pi = d?.detail?.data.i || '1'
				if (!d) {
					let dom = this.selectComponent(`#utools-parse >>> #${id}`)
					dom.select(true, 'scroll')
				}
				if (d && !this.idList.includes('foldPanel' + pi)) {
					this.idList += 'foldPanel' + pi
				}
				let a = setTimeout(async () => {
					this.floorNavData = await this.initloorNavigation()
					clearTimeout(a)
				}, 700)
			},
			//获取购物车商品列表
			getCartList: async function() {
				let that = this;
				let cart_key = uni.getStorageSync(CART_KEY);
				let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
				try {
					if (jwt && cart_key !== null) {
						that.$commonFunction.getCartList().then((res) => {
							if (res && res.items !== null) {
								getApp().globalData.cartNum = res.availableTotalQty;
								that.cartNum = res.availableTotalQty;
								that.$store.commit('changeCartNum', res.availableTotalQty);
								uni.setStorageSync('cartNum', res.availableTotalQty);
							}
						}).catch((err) => {
							that.handleShowTextToast(err.msg);
						});
					}
				} catch (err) {
					console.log(err)
				}
			},
			onAddCart(e) {
				const {
					data
				} = e.detail
				this.goods = data;
				this.addCart(data)
			},
			onTriggerComponent(e) {
				try {

					this.$commonUtoolsTrack.onTriggerComponent(e);
				} catch (e) {
					console.log("home-onTriggerComponent-error:", e)
				}
			},

			// 商品加入购物车功能
			async addCart(data) {
				try {
					this.goodsId = data.itemId
					let that = this
					let merchantInfo = uni.getStorageSync('merchantInfo');
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					let userInfo = uni.getStorageSync(USER_INFO);
					if (!customerInfo && !userInfo) {
						that.registerType = 'cart';
						that.getUserProfile();
						return false;
					} else if (!customerInfo && !!userInfo) {
						that.registerType = 'cart';
						that.$refs.registerWidgetRef.openJoinMemberModal()
						return false;
					}
					let goodsInfo = await this.getGoodsDetail(merchantInfo)
					if (!goodsInfo || goodsInfo.code != 1000) return this.handleCartToast({
						success: false,
						msg: "加入购物车失败"
					});
					// 加入购物车
					const cartRes = await this.$commonFunction.buildProductsAddCart({
						price: goodsInfo.data.skus[0].price,
						itemId: goodsInfo.data.itemId,
						valueId: goodsInfo.data.frontProperties[0].valueId,
						itemCode: goodsInfo.data.itemId,
						itemName: goodsInfo.data.itemName,
						qty: 1,
						skuCode: goodsInfo.data.skus[0].skuCode,
						skuId: goodsInfo.data.skus[0].skuId,
					});
					//  加入购物车提示
					this.handleCartToast(cartRes);
				} catch (e) {
					this.handleCartToast({
						success: false,
						msg: "加入购物车失败"
					});
				}
			},
			/**
			 * 加购提示
			 * @param {Object} obj
			 */
			async handleCartToast(obj) {
				const _arr = ['您动作太快，请慢点哟～', '网络状态不佳，请重试'];
				if(obj.msg && _arr.includes(obj.msg)){
					this.handleShowTextToast(obj.msg)
				}else if(obj.data && obj.data.msg && obj.data.type === 'showToast'){
					this.handleShowTextToast(obj.data.msg)
				}else{
					if (obj?.success) this.getCartList();
					this.cartMessage = obj?.msg || "加入购物车失败";
					this.cartStatus = obj?.success || false;
					this.showCartMsg = true;
					setTimeout(() => {
						this.showCartMsg = false;
					}, 3000);
				}
			},
			//获取商品详情
			async getGoodsDetail(merchantInfo, itemId) {
				const _itemId = itemId || this.goodsId;
				const json = await api.goodsDetail({
						query: {
							merchant_id: merchantInfo.cloudMerchantId,
							store_id: merchantInfo.cloudMerchantStoreId
						}
					},
					_itemId
				);
				return json
			},
			getUserProfile: async function() {
				let that = this
				this.$commonFunction.commonLoginNew().then(res => {
					if (res.code !== 1000) {
						this.$refs.registerWidgetRef.openJoinMemberModal()
					} else if (res.data && res.data.mobile) {
						//  非大陆手机号按照非会员对待,重新入会
						const phoneNumberReg = /^1\d{10}$/;
						if (!phoneNumberReg.test(res.data.mobile)) {
							this.$refs.registerWidgetRef.openJoinMemberModal()
						}
					}
				}).catch(err => {
					this.$refs.registerWidgetRef.openJoinMemberModal()
				})
			},
			/** 21岁弹窗确认 */
			onRegisterWidgetFinish(e) {
				return null
			},
			async registerSuccess() {
				let that = this
				that.showRegister = 1
				return null
				// that.$refs.cmsPage.toParseRegisterSuccess()
			},
			async onShareAppMessage(res) {
				if (res.from === 'button') {} else {
					this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
				}
				let path = '/pages/item/categoryNew'
				this.$commonSensors.sensorsPageShare()
				this.$sr.setContext({ share_title: this.shareTitle || 'THE MACALLAN EBOUTIQUE麦卡伦' });
				return this.$commonFunction.commonShare(res, this.shareTitle, path, this.shareImage)
			},
			onShareTimeline() {
				return {
					title: this.shareTitle,
					query: '',
					imageUrl: this.shareImage
				};
			},
		},
		async getTsBySku(tsId, api) {
			let customerInfo = wx.getStorageSync('customerInfo');
			let merchantInfo = wx.getStorageSync('merchantInfo');
			let memberDetails = wx.getStorageSync('memberDetails');
			let query = {
				"store_id": merchantInfo.cloudMerchantStoreId,
				"sku_id": this.productSKU,
				"group_id": customerInfo.groupId,
				"member_level_id": memberDetails.memberLevelId,
				"merchant_id": merchantInfo.cloudMerchantId,
				'campaign_target_sale_id': tsId || ''
			}
			const result = await api.getTsBySku({
				header: {
					jwt: customerInfo.jwt
				},
				method: 'GET',
				query: query,
			});
			if (result.code == 1000) {
				let {

					campaignStartTime,
					status
				} = result.data
				this.tsInfo = result.data
				let now = new Date().getDate()
				this.startTime = this.formatTimeStamp(campaignStartTime) // 开始
				return now > this.startTime
			} else {
				return false
			}

		},
		formatTimeStamp(date) {
			let systemInfo = wx.getSystemInfoSync()
			let isIos = systemInfo.system.indexOf("iOS");
			if (isIos == 0) {
				date = date && new Date(date.replace(/-/g, "/")).getTime();
			} else {
				date = date && new Date(date).getTime();
			}
			return date;
		},


	}
</script>

<style lang="less">
	page {
		background-color: #f6f5f3 !important;
	}


	.doubleMargin {
		margin-top: 105rpx !important;
	}

	.defaultMargin {
		margin-top: 60rpx !important;
	}

	::-webkit-scrollbar {
		display: none;
		width: 0;
		height: 0;
		color: transparent;
	}
</style>
